package com.zzy.furns.dao.impl;

import com.zzy.furns.dao.BasicDAO;
import com.zzy.furns.dao.FurnDAO;
import com.zzy.furns.domain.Furn;
import com.zzy.furns.domain.Page;

import java.util.List;

public class FurnDAOImpl extends BasicDAO<Furn> implements FurnDAO {
    @Override
    public List<Furn> queryFurns() {
        String sql = "SELECT id,name,maker,price,sales,stock,img_path As imgPath FROM furn";
        return queryMulti(sql, Furn.class);
    }

    @Override
    public Integer add(Furn furn) {
        String sql = "INSERT INTO furn(`name`,`maker`,`price`,`sales`,`stock`,`img_path`)" +
                "VALUES(?,?,?,?,?,?)";
        return update(sql, furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath());
    }

    @Override
    public Integer deleteFurnById(Integer id) {
        String sql = "DELETE FROM furn WHERE id = ?";
        return update(sql, id);
    }

    @Override
    public Furn queryFurnById(Integer id) {
        String sql = "SELECT id,`name`,maker,price,sales,stock,img_path As imgPath FROM furn WHERE id = ?";
        return querySingle(sql, Furn.class, id);
    }

    @Override
    public Integer updateFurn(Furn furn) {
        String sql = "UPDATE furn SET `name` = ? ,maker = ? ,price = ? ,sales = ? ,stock = ? ,img_path = ? WHERE id = ?";
        return update(sql, furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath(), furn.getId());
    }

    @Override
    public Integer getTotalRow() {
        /**
         * 注意：Java中执行聚合函数COUNT(*)的SQL语句 SELECT COUNT(*) FROM furn 返回值的运行类型是 Long
         * 此时
         *      Integer rowTotal = (Integer)queryScalar(sql);
         * 会报错 java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Integer
         *
         * () 这种强制类型转换方式只适用于基本数据类型，包装类之间的转换需要调用对应的方法
         */
        String sql = "SELECT COUNT(*) FROM furn";
        Number number = (Number) queryScalar(sql);
        return number.intValue();
    }

    @Override
    public List<Furn> getPageItems(Integer begin, Integer pageSize) {
        String sql = "SELECT id,`name`,maker,price,sales,stock,img_path As imgPath FROM furn LIMIT ?,?";
        return queryMulti(sql, Furn.class, begin, pageSize);
    }

    @Override
    public Integer getPageTotalCountByName(String name) {
        String sql = "SELECT COUNT(*) FROM furn WHERE `name` like '%" + name + "%'";
        //queryScalar(sql)结果的运行类型是Long
        //instanceof判断的是运行类型
        return Integer.parseInt(queryScalar(sql).toString());
    }

    @Override
    public List<Furn> getPageItemsByName(String name, Integer index, Integer pageSize) {
        String sql = "SELECT id,`name`,maker,price,sales,stock,img_path As imgPath FROM furn WHERE `name` like '%" + name + "%' LIMIT ?,?";
        return queryMulti(sql, Furn.class,index,pageSize);
    }

}
